
#include "RoceReceiverManager.h"

namespace ai_sim {

RoceReceiverManager::RoceReceiverManager() {
  //finishedFlows.clear();
  expectedSeq  = 0;
}

int RoceReceiverManager::processReceivedPacket(uint32_t seqNum, bool isLastSegment, const ai_sim::Flow& flow) {
  if (seqNum == expectedSeq) {
    // ACK 
    expectedSeq++;
    if (flow.flowId != currentFlowId) {
      currentFlowId = flow.flowId;
      cummulativeFlowSize = 0;
    }
    cummulativeFlowSize += flow.data_size;
    if (isLastSegment) {
      Flow flow_copy = flow;
      flow_copy.data_size = cummulativeFlowSize;
      finishedFlows.push(flow_copy);
      cummulativeFlowSize = 0;
    }
    return 1;
  } else if (seqNum > expectedSeq) {
    // NACK
    return 2;
  }
  return -1;
}

uint32_t RoceReceiverManager::getAckSeqNum() {
  return expectedSeq;
}

bool RoceReceiverManager::hasFinishedFlow() {
  if (finishedFlows.empty()) {
    return false;
  }
  return true;
}

Flow RoceReceiverManager::getFinishedFlow() {
  if (finishedFlows.empty()) {
    std::cout << "error: finishedFlows should not be empty!" << std::endl;
    assert(false);
  }
  auto ret = finishedFlows.front();
  finishedFlows.pop();
  return ret;
}

}